package org.linlinjava.litemall.wx.web;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ibatis.annotations.Param;
import org.linlinjava.litemall.core.util.JacksonUtil;
import org.linlinjava.litemall.core.util.MD5Util;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.LitemallBrand;
import org.linlinjava.litemall.db.domain.LitemallOrder;
import org.linlinjava.litemall.db.domain.LitemallOrderReport;
import org.linlinjava.litemall.db.service.LitemallBrandService;
import org.linlinjava.litemall.db.service.LitemallOrderReportService;
import org.linlinjava.litemall.db.service.LitemallOrderService;
import org.linlinjava.litemall.wx.service.CaptchaCodeManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.LinkedHashMap;
import java.util.Map;

@RestController
@RequestMapping("wx/report/")
public class WxReportController {
    private  final Log log= LogFactory.getLog(WxReportController.class);
    @Autowired
    LitemallOrderService orderService;
    @Autowired
    LitemallBrandService brandService;
    @Autowired
    LitemallOrderReportService reportService;

    /**
     * 校验 文件格式
     * @param file 文件  不许docx  doc  png 格式的上传
     * @param msg  phone手机号  captcha 验证码
     * @return
     */
    @PostMapping("verify")
    public Object verify(@RequestParam MultipartFile file, @RequestParam String msg) {
        try {
            String fileName = file.getOriginalFilename();
            assert fileName != null;
            String type = fileName.substring(fileName.lastIndexOf('.') + 1);
            if (StringUtils.isEmpty(type) || "docx".equalsIgnoreCase(type) || "doc".equalsIgnoreCase(type) || "png".equalsIgnoreCase(type)) {
                return ResponseUtil.badArgument();
            }
            String phone = JacksonUtil.parseString(msg, "phone");
            String captcha = JacksonUtil.parseString(msg, "captcha");
            if (StringUtils.isAnyEmpty(phone, captcha)) {
                return ResponseUtil.badArgument();
            }
            String trueCode = CaptchaCodeManager.getCachedCaptcha(phone);
            if (!captcha.equals(trueCode)) {
                return ResponseUtil.fail(402, "验证码不正确");
            }
            InputStream inputStream = file.getInputStream();
            String md5 = MD5Util.getMD5(inputStream);
            LitemallOrderReport report = reportService.selectByMd5(md5);
            if (report != null) {
                LitemallOrder order = orderService.findById(report.getOrderId());
                LitemallBrand brand = brandService.findById(order.getBrandId());
                Map<String, Object> map = new LinkedHashMap<>();
                map.put("exist", true);
                map.put("uploadDate", report.getCreateTime());
                map.put("orderSn", order.getOrderSn());
                map.put("brand", brand.getName());
                return ResponseUtil.ok(map);
            } else {
                Map<String, Object> map = new LinkedHashMap<>();
                map.put("exist", false);
                return ResponseUtil.ok(map);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtil.fail(500, e.getMessage());
        }
    }



    /**
     * 下载report报表上传的报告..从 storage 中复制而来 的不可使用..改一个下载文件流.返回前端,前端转成文件..4.30号王宁帮助薛测试完成
     **/
    @GetMapping("/down")
    public void down(@Param(value = "fileName") String fileName, HttpServletRequest request, HttpServletResponse response) {
        System.out.println("fileName>>>>>" + fileName);
        String type = fileName.split("_")[0];
        if ("report".equals(type)) {
            LitemallOrderReport storageInfo = reportService.findByName(fileName);
            if ("order".equals(storageInfo.getType())) {
                LitemallOrder order = orderService.findById(storageInfo.getOrderId());
                System.out.println("order>>>>>" + order);
                //取消单点的拦截.直接从订单中获取.用户ID..
                //  XxlSsoUser user = (XxlSsoUser) request.getAttribute(Conf.SSO_USER);
                // String userId = user.getUserid();
                String userId = String.valueOf(order.getUserId());
                System.out.println("userId>>>>>" + userId);
                if (!order.getUserId().toString().equals(userId)) {
                    ResponseEntity.badRequest().build();
                }
                String realPath = System.getProperty("user.dir");
                System.out.println("realPath>>>" + realPath );
                File file = new File(realPath + "/report/" + fileName);
                System.out.println("file>>>" + file );
                if (fileName != null) {
                    // 如果文件存在，则进行下载
                    if (file.exists()) {
                        // 配置文件下载
                        response.setHeader("content-type", "application/octet-stream");
                        response.setContentType("application/octet-stream");
                        // 下载文件能正常显示中文
                        try {
                            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                        // 实现文件下载
                        byte[] buffer = new byte[1024];

                        FileInputStream fis = null;
                        BufferedInputStream bis = null;
                        try {
                            fis = new FileInputStream(file);
                            bis = new BufferedInputStream(fis);
                            response.setHeader("Content-Length", fis.available() + "");
                            response.setContentType("application/octet-stream");
                            OutputStream os = response.getOutputStream();
                            int i = bis.read(buffer);
                            while (i != -1) {
                                os.write(buffer, 0, i);
                                i = bis.read(buffer);
                            }
                            log.info("下载成功!" + fileName);
                        } catch (Exception e) {
                            log.info("下载失败！！！!");
                        } finally {
                            if (bis != null) {
                                try {
                                    bis.close();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                            if (fis != null) {
                                try {
                                    fis.close();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                }
            }

        }

    }



}
